package com.ww.springboot.boot.algorithm.leetcode1;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-03-10 16:39
 */
public class AF48旋转图像 {
    public static void main(String[] args) {
        //int[][] matrix = {{5,1,9,11}, {2,4,8,10}, {13,3,6,7},{15,14,12,16}};
        //int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] matrix = {{1, 2}, {3,4}};
        //int[][] matrix = {{43, 39, 3, 33, 37, 20, 14}, {9, 18, 9, -1, 40, 22, 38}, {14, 42, 3, 23, 12, 14, 32}, {18, 31, 45, 11, 8, -1, 31}, {28, 44, 14, 23, 40, 24, 13}, {29, 45, 33, 45, 20, 0, 45}, {12, 23, 35, 32, 22, 39, 8}};
        //int[][] matrix = {{24,4,38,2,21,18,33,40},{24,37,25,62,37,15,35,36},{42,23,13,58,17,26,19,8},{32,48,9,58,36,18,40,61},{23,16,0,46,35,34,23,60},{9,49,60,47,1,32,20,45},{56,34,40,11,61,60,20,30},{45,30,25,18,49,3,16,10}};
        print(matrix);
        rotate(matrix);
        print(matrix);
    }

    private static void print(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            String ss = "";
            for (int j = 0; j < matrix[i].length; j++) {
                ss += " " + matrix[i][j];
            }
            System.out.println(ss);
        }
        System.out.println("---------------------");
    }

    public static void rotate(int[][] matrix) {
        int length = matrix.length;
        int total = length * length;
        int remainder = length%2;
        if(remainder != 0){
            //如果是奇数 则只用转移length * length-1次 偶数需要转移length * length次
            total--;
        }
        int x = 0, y = 0;
        int n = matrix[x][y];
        int index = 0;
        int flag = 0;
        while (flag < total) {
            //交换数据
            int m = matrix[y][length - 1 - x];
            int x_new = y;
            int y_new = length - 1 - x;
            matrix[x_new][y_new] = n;
            x = x_new;
            y = y_new;
            n = m;
            index++;
            if (index == 4) {
                if (y < length - 2 - x) {
                    y++;
                } else {
                    x++;
                    y = x;
                }
                index = 0;
                n = matrix[x][y];
            }
            flag++;
            print(matrix);
        }
    }
}
